package cn.com.colasoft.utils;

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 查看类、对象占用的内存大小
 * 包含：markword、kclass、数据内容、填充部分
 * </p>
 *
 * @author jian.li5
 * @date 2019/6/28
 */
public class JolCoreDemo {

    public static void main(String[] args) {
        // 打印对象头信息代码
/*        System.out.println(ClassLayout.parseClass(TreeMap.class).toPrintable());
        System.out.println(ClassLayout.parseClass(Fruit.class).toPrintable());*/

        Object obj = generate();
        //查看对象内部信息
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());

        //查看对象外部信息
        System.out.println(GraphLayout.parseInstance(obj).toPrintable());

        //获取对象总大小
        System.out.println("size : " + GraphLayout.parseInstance(obj).totalSize());
    }

    class Fruit extends Object {
        private int size;
    }

    static Object generate() {
        Map<String, Object> map = new HashMap<>(10);
        map.put("a", new Integer(1));
        map.put("b", "b");
        map.put("c", new Date());

        for (int i = 0; i < 10; i++) {
            map.put(String.valueOf(i), String.valueOf(i));
        }
        return map;
    }
}


